package com.benyq.networkprogramme

import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.MenuItem
import com.benyq.networkprogramme.base.bean.Msg
import com.benyq.networkprogramme.base.bean.MsgEvent
import com.benyq.networkprogramme.tcp.OnReceivedListener
import com.benyq.networkprogramme.tcp.TcpService
import com.benyq.networkprogramme.udp.UdpSender
import kotlinx.android.synthetic.main.activity_chat.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.*

class ChatActivity : AppCompatActivity(){

    private lateinit var tcpBinder: TcpService.TcpServiceBinder
    private val msgAdapter: MsgAdapter by lazy { MsgAdapter(this) }

    private val serviceConnection = object: ServiceConnection {
        override fun onServiceDisconnected(p0: ComponentName?) {
        }

        override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
            tcpBinder = p1 as TcpService.TcpServiceBinder
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_chat)

        initView()
        val ip = intent.getStringExtra("ipAddress")
        val port = intent.getIntExtra("port", -1)
        Intent(this, TcpService::class.java).run {
            putExtra("ipAddress", ip)
            putExtra("port", port)
            bindService(this, serviceConnection, Context.BIND_AUTO_CREATE)
        }
    }

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        if (item?.itemId == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onStop() {
        EventBus.getDefault().unregister(this)
        super.onStop()
    }

    override fun onDestroy() {
        unbindService(serviceConnection)
        super.onDestroy()
    }

    private fun initView(){
        val name = intent.getStringExtra("name")
        mainToolbar.title = name
        setSupportActionBar(mainToolbar)
        mainToolbar.navigationIcon = ContextCompat.getDrawable(this, R.drawable.ic_action_back)

        rvMsg.layoutManager = LinearLayoutManager(this)
        rvMsg.adapter = msgAdapter

        btnSend.setOnClickListener {
            val msg = etMsg.text.toString() + SimpleDateFormat("hh:mm:SSS", Locale.CHINA).format(Date())
            msgAdapter.add(Msg(Msg.type_sent, msg))
            rvMsg.scrollToPosition(msgAdapter.datas.size - 1)
            if (tcpBinder.isConnectd()){
                tcpBinder.sendMessage(msg)
            }else {
                UdpSender.send(msg)
                Log.e("susan", "chat$msg")
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventReceived(msgEvent: MsgEvent){
        val msg = Msg(Msg.type_received, msgEvent.msg)
        msgAdapter.add(msg)
        rvMsg.scrollToPosition(msgAdapter.datas.size - 1)
    }
}
